import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
import { CommonService } from '../common.service';

@Injectable()
export class TokenAuth implements CanActivate {
  constructor(private common: CommonService) {}

  async canActivate(context: ExecutionContext) {
    // console.log(context.switchToHttp().getRequest().headers)
    let authorization = (context.switchToHttp().getRequest() as Request).headers['authorization'];

    if (!authorization) {
      throw new HttpException('未认证的用户', 401);
    }
    if (!authorization.includes('Bearer')) {
      throw new HttpException('token格式错误', 401);
    }

    let result = '';
    try {
      result = this.common.checkToken(authorization.replace('Bearer', '').trim());
    } catch (error) {
      throw new HttpException(error.message, 401);
    }
    let val = await this.common.UserTokenClient.get(String((result as any).id));
    //  console.log(val,authorization)
    if (val != authorization.replace('Bearer', '').trim()) {
      throw new HttpException('token失效', 401);
    }
    //  console.log(result)

    context.switchToHttp().getRequest().user_info = result;
    return true;
    // throw new Error('Method not implemented.');
  }
}
